package com.tanhua.server.service;

import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.domain.db.Announcement;
import com.tanhua.domain.db.PageResult;
import com.tanhua.domain.vo.AnnouncementVo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.dubbo.api.AnnouncementApi;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class AnnouncementService {

    //订阅AnnouncementApi服务
    @Reference
    private AnnouncementApi announcementApi;

    /**
     * 查询公告信息
     */
    public PageResult<AnnouncementVo> getAnnouncements(Integer page, Integer pagesize) {

        //调用AnnouncementApi接口的方法
        PageResult<Announcement> announcements = announcementApi.getAnnouncements(page, pagesize);
        //判断announcements的itmes对象是否为null
        if(announcements==null||announcements.getItems().size()<=0){
            throw new TanHuaException(ErrorResult.gonggaoFailed());
        }
        //创建一个pageResult对象
        PageResult<AnnouncementVo> pageResultVo = new PageResult<>();
        //复制对象属性到pageResultVo
        BeanUtils.copyProperties(announcements,pageResultVo);
        //创建List<AnnouncementVo>集合
        ArrayList<AnnouncementVo> announcementVos = new ArrayList<>();
        for (Announcement item : announcements.getItems()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(item.getId()+"");
            announcementVo.setTitle(item.getTitle());
            announcementVo.setDescription(item.getDescription());
            announcementVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh:mm").format(item.getCreated()));
            announcementVos.add(announcementVo);
        }
        pageResultVo.setItems(announcementVos);
        //返回响应体
        return pageResultVo;
    }






}
